package model

import (
	"encoding/json"
	"fmt"
	"github.com/garyburd/redigo/redis"
	"mass-user/commons/user"
)

type UserDAO struct {
	pool *redis.Pool
}

var userDao *UserDAO

func (d UserDAO) AddUser() {

}


func NewUserDao(pool *redis.Pool) *UserDAO {
	userDao = &UserDAO{pool:pool}
	return userDao
}

func GetUserDao() *UserDAO {
	return userDao
}

func (d UserDAO) GetById(id int, conn redis.Conn) (*user.User, error) {
	res, err := redis.String(conn.Do("HGet", "users", id))
	if err != nil {
		if err == redis.ErrNil {
			err = ERR_USER_NOTEXISTS
			return nil, err
		}
	}
	var user user.User
	err = json.Unmarshal([]byte(res), &user)
	if err != nil {
		return nil, err
	}
	return &user, nil

}

func (d UserDAO) Login(id int, pwd string) (*user.User, error) {
	conn := d.pool.Get()
	user, err := d.GetById(id, conn)
	//defer conn.Close()
	if err != nil {
		return nil, err
	}
	if user.Pwd == pwd {
		return user, nil
	} else {
		return nil, ERR_USER_PWD
	}
}

func (d UserDAO) Reg(user *user.User) error  {
	conn := d.pool.Get()
	//defer conn.Close()
	_, err := d.GetById(user.UserId, conn)
	if err == nil{
		return ERR_USER_EXISTS
	}else{
		data, err := json.Marshal(user)
		if err != nil{
			return err
		}
		_, err = conn.Do("hset", "users", user.UserId, string(data))
		if err != nil{
			fmt.Println("入库失败")
			return err
		}
	}
	return nil
}